package com.gaofei.order.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaofei.order.domain.TbCart;
import com.gaofei.order.domain.TbGoods;
import com.gaofei.order.domain.TbOrder;
import com.gaofei.order.service.TbCartService;
import com.gaofei.order.service.TbGoodsService;
import com.gaofei.order.service.TbOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @Title: OrderController
 * @Author gaofee
 * @Package com.gaofei.order.controller
 * @Date 2024/03/12 16:26
 * @description: 订单接口
 */
@RequestMapping("order")
@RestController
public class OrderController {
    @Autowired
    private TbOrderService orderService;

    @Autowired
    private TbGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbCartService cartService;

    /**
     * 导出订单对账单
     */
    @RequestMapping("exportOrderBill")
    public void exportOrderBill(HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<TbOrder> list = orderService.list();
        EasyExcel.write(response.getOutputStream(), TbOrder.class).sheet("对账单1").doWrite(list);
    }


    /**
     * 查询所有未支付的订单
     * @param status
     * @return
     */
    @RequestMapping("queryOrdersOfNoPay")
    public List<TbOrder> queryOrdersOfNoPay(@RequestParam("status") String status){
        QueryWrapper<TbOrder> tbCartQueryWrapper = new QueryWrapper<>();
        tbCartQueryWrapper.eq("order_status", status);
        List<TbOrder> list = orderService.list(tbCartQueryWrapper);
        return list;
    }

    @RequestMapping("updateOrderStatus")  //远程调用这里加上这个注解
    public String update(@RequestParam("orderId") String orderId){
        TbOrder byId = orderService.getById(orderId);
        byId.setOrderStatus("已支付");
        byId.setUpdateTime(new Date());
        orderService.updateById(byId);
        return "success";
    }

    /**
     * 订单列表
     * @return
     */
    @RequestMapping("orderList")
    public Object orderList(){
        QueryWrapper<TbOrder> tbCartQueryWrapper = new QueryWrapper<>();
        tbCartQueryWrapper.eq("user_id", 1);
        List<TbOrder> list = orderService.list(tbCartQueryWrapper);
        return list;
    }

    @RequestMapping("getTotalPriceByUid")
    @Transactional//本地事务控制
    @GlobalTransactional(rollbackFor = Exception.class) //分布式事务处理方案
    public Object getTotalPriceByUid(){
        //计算总价格
        QueryWrapper<TbCart> tbCartQueryWrapper = new QueryWrapper<>();
        tbCartQueryWrapper.eq("user_id", 1);
        List<TbCart> list = cartService.list(tbCartQueryWrapper);
        BigDecimal bigDecimal = new BigDecimal("0");
        StringBuffer goodsIds = new StringBuffer();
        for (TbCart tbCart : list) {
            bigDecimal=  bigDecimal.add(tbCart.getTotalPrice());
            goodsIds.append(tbCart.getGoodsId()+",");
        }
        //创建订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderStatus("待支付");
        tbOrder.setGoodsId(goodsIds.toString());
        tbOrder.setUserId(1);
        tbOrder.setTotalAmount(bigDecimal);
        tbOrder.setCreateTime(new Date());
        orderService.save(tbOrder);
//        int i = 1/0;
        //返回orderId 和 总价格
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId", tbOrder.getId());
        map.put("amount",bigDecimal);
        map.put("msg","success");
        return map;

    }



    /**
     * 删除购物车
     * @param tbCart
     * @return
     */

    @RequestMapping("delCartInfo")
    public Object del(@RequestBody TbCart tbCart){

        cartService.removeById(tbCart.getId());
        return "success";
    }
    @RequestMapping("updateCartInfo")
    public Object updateCartInfo(@RequestBody TbCart tbCart){

        TbCart dbcart = cartService.getById(tbCart.getId());
        //根据商品id查询商品价格
        TbGoods dbgoods = goodsService.getById(tbCart.getGoodsId());
        dbcart.setBuyNum(tbCart.getBuyNum());
        dbcart.setTotalPrice(dbgoods.getGoodsPrice().multiply(new BigDecimal(tbCart.getBuyNum())));

        //更新到数据库
        cartService.updateById(dbcart);

        return "success";
    }

    @RequestMapping("cartList")
    public Object cartList(){
        List<TbCart> list = cartService.list();
        return list;
    }


    @RequestMapping("addCart")
    public Object addCart(@RequestBody TbGoods goods){
        //1.根据用户id和商品id 查询是否有对应的购物车数据
        QueryWrapper<TbCart> qw = new QueryWrapper<>();
        qw.eq("goods_id", goods.getId());
        qw.eq("user_id", "1");
        TbCart one = cartService.getOne(qw);
        //2.如果有对应数据,更新购物车(合并购物项)
        if(one!=null){
            one.setBuyNum(one.getBuyNum()+1);
            one.setTotalPrice(goods.getGoodsPrice().add(one.getTotalPrice()));
            cartService.updateById(one);
            redisTemplate.delete("goodsList");
            redisTemplate.opsForList().leftPush("goodsList",one);
            return "success";
        }

        //首次加入购物车
        TbCart tbCart = new TbCart();
        tbCart.setBuyNum(1);
        tbCart.setGoodsId(goods.getId());
        tbCart.setTotalPrice(goods.getGoodsPrice());
        tbCart.setUserId(1);
        //将tbCart存入数据库
        cartService.save(tbCart);
        redisTemplate.opsForList().leftPush("goodsList",tbCart);
        return "success";
    }

    @RequestMapping("list")
    public Page list(Page page,String keyword){
        QueryWrapper<TbGoods> qw = new QueryWrapper<>();
        if(StrUtil.isNotBlank(keyword)){
            qw.like("goods_name", keyword);
        }
        Page page1 = goodsService.page(page, qw);
        return page1;
    }
}
